import 'package:cached_network_image/cached_network_image.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:common_utils/common_utils.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/views/search_appbar.dart';

import '../entity/product_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/common_utils.dart';
import '../views/dialog_manager.dart';

///
/// 商品分类/搜索列表
///
class ProductListPage extends StatefulWidget {
  var cateId = '';
  var keyword = '';
  var sourceId = '';

  ProductListPage({Key? key, this.cateId = '', this.keyword = '', this.sourceId = ''})
      : super(key: key);

  @override
  State<ProductListPage> createState() => _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {
  var _menuIndex = 1;

  //可选值all(综合排序), price（价格排序 默认值）,sales(销量排序)
  var order_by = 'all';

  var sort = 'desc';

  List<ProductData> datas = [];
  var page = 1;

  @override
  void initState() {
    super.initState();
    getProducts();
  }

  getProducts() async {
    var param = {
      'page': page.toString(),
      'size': '20',
      'order_by': order_by,
    };
    if (order_by == 'price') {
      param['sort'] = sort;
    }
    if (widget.cateId.isNotEmpty) {
      param['cate_id'] = widget.cateId;
    }
    if (widget.keyword.isNotEmpty) {
      param['keyword'] = widget.keyword;
    }
    if (widget.sourceId.isNotEmpty) {
      param['source_id'] = widget.sourceId;
    }
    dynamic result = await Api.goodsList(param);
    ProductEntity entity = ProductEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  //返回商品列表item
  getListItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.productDetail, params: {'productId': datas[index].id});
      },
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10.w),
                topRight: Radius.circular(10.w),
              ),
              child: CachedNetworkImage(
                imageUrl: CommonUtils.compressImageUrl(datas[index].mainImg, 500, 500),
                fit: BoxFit.fill,
                width: double.infinity,
                height: 330.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: double.infinity,
                    height: 330.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
            ),
            Padding(padding: EdgeInsets.all(5.w)),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              width: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(padding: EdgeInsets.only(top: 2.w)),
                  Text(
                    datas[index].name,
                    softWrap: false,
                    style: TextStyle(color: Config.colorText1, fontSize: 28.sp),
                  ),
                  Padding(padding: EdgeInsets.only(top: 10.w)),
                  Text(
                    CommonUtils.formatAmountUnit(datas[index].money, datas[index].company,
                        datas[index].money1, datas[index].company1),
                    softWrap: false,
                    style: TextStyle(color: Colors.redAccent, fontSize: 24.sp),
                  ),
                  Padding(padding: EdgeInsets.only(top: 10.w)),
                  InkWell(
                    onTap: () {
                      Routes.navigateTo(context, Routes.mallHome,
                          params: {'storeId': datas[index].storeId});
                    },
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          datas[index].store.name,
                          softWrap: false,
                          style: TextStyle(color: Config.colorText1, fontSize: 24.sp),
                        ),
                        Text(
                          '进店 >',
                          softWrap: false,
                          style: TextStyle(color: Config.colorText1, fontSize: 24.sp),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: SearchAppBar(
          hintLabel: widget.keyword,
          callBack: (str) {
            FocusManager.instance.primaryFocus?.unfocus();
            widget.keyword = str;
            page = 1;
            getProducts();
            // LogUtil.v(str);
          },
        ),
        centerTitle: true,
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Container(
              height: 80.w,
              width: double.infinity,
              decoration: BoxDecoration(color: Config.colorWhite),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  InkWell(
                    onTap: () {
                      setState(() {
                        _menuIndex = 1;
                        order_by = 'all';
                        page = 1;
                        getProducts();
                      });
                    },
                    child: Container(
                      width: 76.w,
                      child: Text(
                        '综合',
                        style: TextStyle(
                            fontSize: 25.sp,
                            color: _menuIndex == 1 ? Config.colorMain : Config.colorText1),
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      setState(() {
                        _menuIndex = 2;
                        order_by = 'sales';
                        page = 1;
                        getProducts();
                      });
                    },
                    child: Text(
                      '销量',
                      style: TextStyle(
                          fontSize: 25.sp,
                          color: _menuIndex == 2 ? Config.colorMain : Config.colorText1),
                    ),
                  ),
                  Stack(
                    children: [
                      InkWell(
                        onTap: () {
                          setState(() {
                            if (_menuIndex == 3) {
                              _menuIndex = 4;
                              sort = 'asc';
                            } else {
                              _menuIndex = 3;
                              sort = 'desc';
                            }
                            order_by = 'price';
                            page = 1;
                            getProducts();
                          });
                        },
                        child: Container(
                          width: 76.w,
                          child: Text(
                            '价格',
                            style: TextStyle(
                                fontSize: 25.sp,
                                color: (_menuIndex == 3 || _menuIndex == 4)
                                    ? Config.colorMain
                                    : Config.colorText1),
                          ),
                        ),
                      ),
                      Visibility(
                        visible: _menuIndex == 3 || _menuIndex == 4,
                        child: Container(
                          width: 76.w,
                          height: 37.w,
                          alignment: Alignment.centerRight,
                          child: Image.asset(
                            _menuIndex == 3
                                ? 'assets/images/icon_price_desc.png'
                                : 'assets/images/icon_price_ase.png',
                            width: 20.w,
                            height: 25.w,
                            color: Config.colorMain,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Container(
              height: double.infinity,
              width: double.infinity,
              margin: EdgeInsets.only(top: 80.w),
              child: EasyRefresh(
                header: const MaterialHeader(),
                footer: const MaterialFooter(),
                onRefresh: () async {
                  page = 1;
                  getProducts();
                },
                onLoad: () async {
                  getProducts();
                },
                child: GridView.builder(
                  padding: EdgeInsets.symmetric(horizontal: 25.w, vertical: 20.w),
                  itemCount: datas.length,
                  // shrinkWrap: true,
                  // scrollDirection: Axis.vertical,
                  // physics: const BouncingScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return getListItem(index);
                  },
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      mainAxisSpacing: 19.w,
                      crossAxisSpacing: 19.w,
                      childAspectRatio: 0.70),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
